#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h> // Added for close()

#define PORT 8888 // Define port consistently

int main(int argc, char **argv)
{
    struct sockaddr_in s_addr, c_addr;
    int sock;
    socklen_t addr_len;
    ssize_t len; // Use ssize_t for recvfrom/sendto return
    char buf[128];
    char buf2[128];
    int recdata = 0; // Removed redundant initialization '=0' inside declaration

    if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
    { // Corrected check: == -1
        perror("socket");
        exit(1);
    }
    else
    {
        printf("create socket connected.\n"); // Corrected typo
    }

    memset(&s_addr, 0, sizeof(struct sockaddr_in));
    s_addr.sin_family = AF_INET;
    s_addr.sin_port = htons(PORT);       // Use defined PORT
    s_addr.sin_addr.s_addr = INADDR_ANY; // Bind to all interfaces

    if ((bind(sock, (struct sockaddr *)&s_addr, sizeof(s_addr))) == -1)
    {
        perror("bind failed"); // Removed \n, perror adds it
        close(sock);
        exit(1);
    }
    else
    {
        printf("bind address to socket.\n"); // Corrected typo
    }

    printf("UDP Server listening on port %d...\n", PORT);

    while (1)
    {
        addr_len = sizeof(c_addr);   // Initialize addr_len before recvfrom
        memset(buf, 0, sizeof(buf)); // Clear buffer before receiving

        len = recvfrom(sock, buf, sizeof(buf) - 1, 0, (struct sockaddr *)&c_addr, &addr_len);

        if (len < 0)
        {
            // Check for interrupt
            if (errno == EINTR)
            {
                continue;
            }
            perror("recvfrom error");
            // Decide whether to continue or exit on error
            continue; // Continue listening
                      // exit(errno); // Original behavior
        }

        buf[len] = '\0';                                // Null-terminate received data
        printf("receive came from %s:%d message: %s\n", // Corrected typo
               inet_ntoa(c_addr.sin_addr), ntohs(c_addr.sin_port), buf);

        recdata = atoi(buf);
        recdata++;
        sprintf(buf2, "%d", recdata);

        // Send response back to the client address obtained from recvfrom
        ssize_t sent_len = sendto(sock, buf2, strlen(buf2), 0, (struct sockaddr *)&c_addr, addr_len);
        if (sent_len < 0)
        {
            perror("sendto error");
            // Handle error
        }
        else
        {
            printf("Sent response: %s to %s:%d\n", buf2, inet_ntoa(c_addr.sin_addr), ntohs(c_addr.sin_port));
        }
    } // End while(1)

    close(sock); // Close socket (though loop is infinite)
    return 0;
}